const BaseService = require("./BaseService.js")
const moment = require('moment')

class MenuService extends BaseService {
  // 菜单列表
  async list(params){
    let menu = await this.Db('menu').select();
    let menuTree = this.getTree(menu)
    return menuTree
  }

  // 树结构
  getTree(menu){
    return menu.filter(father=>{
      // 返回每一项的子项
      let children = menu.filter(child=>father.id == child.uid)
      children.length > 0 ? father['children'] = children : father['children'] = []
      return father.uid == 0 // 返回第一层
    })
  }

  // 创建根菜单或子菜单
  async create(params){
    let result = await this.Db('menu').where('en_name','=',params.en_name).find()
    if(typeof result == 'object'){
      return false
    }else{
      this.Db('menu').insert({
        name: params.name,
        en_name: params.en_name,
        uid: params.uid,
        isAlwaysShow: params.isAlwaysShow == true ? 1 : 2,
        create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        update_time: moment().format('YYYY-MM-DD HH:mm:ss')
      });
      return true
    }
  }

  // 编辑菜单
  async edit(params){
    let result = await this.Db('menu').where('id','=',params.id).find()
    // 没有修改名称
    if(result.en_name == params.en_name){
      this.Db('menu').where('id','=',params.id).update({
        name: params.name,
        en_name: params.en_name,
        isAlwaysShow: params.isAlwaysShow == true ? 1 : 2,
        update_time: moment().format('YYYY-MM-DD HH:mm:ss')
      });
      return true
    }else{
      // 修改成已有的名称
      let menu = await this.Db('menu').where('en_name','=',params.en_name).find();
      if(typeof menu == 'object'){
        return false
      }else{
        this.Db('menu').where('id','=',params.id).update({
          name: params.name,
          en_name: params.en_name,
          update_time: moment().format('YYYY-MM-DD HH:mm:ss')
        });
        return true
      }
    }
  }

  // 删除
  async deleteItem(params){
    // 判断是否有角色关联了该菜单
    let result = await this.Db('role').where('menu_ids','like',`%${params.id}%`).find();
    if(typeof result == 'object'){
      return {
        state: false,
        msg: '有角色关联了该菜单，不可删除！'
      }
    }else{
      // 判断是否有子菜单
      let menu = await this.Db('menu').where('uid','=',params.id).find()
      if(typeof menu == 'object'){
        return {
          state: false,
          msg: '有子菜单不可直接删除'
        }
      }else{
        this.Db('menu').where('id','=',params.id).delete()
        return {
          state: true,
          msg: '删除成功！'
        }
      }
    }
  }

}

module.exports = MenuService;